# -*- coding: utf-8 -*-

from pickle import dumps, loads

import os

abspath = os.path.dirname(os.path.realpath(__file__))


class Configuration:
    """
        Configuration class is used as a storage class for 
        application global constants (options). Its pickle 
        is stored in a configuration file.
    """
    language = 'uk'
    
    languages = {
        u'English':u'en',
        u'Русский':u'ru',
        u'Українська':u'uk',
    }

    proxy_host = 'localhost'
    proxy_port = 8080
    proxy_login = ''
    proxy_pass = ''


class ConfigurationManager(object):
    """
        ConfigurationManager class stores application configuration. It
        uses pickle to save Configuration class instance into file.
        
        When creating instance of ConfigurationManager:
          1. Trying to load configuration from file.
          2. If fail - creating default configuration.
         
        Methods:
            save -> saves Configuration instance pickle to file
            load -> loads Configuration instance from file
    """
    
    configuration = None
    configuration_path = os.path.join(abspath, 'configuration.cfg')
    
    def __init__(self):
        configuration_loaded = self.load()
        if not configuration_loaded:
            self.configuration = Configuration()

    def __getitem__(self, key):
        return getattr(self.configuration, key)
    
    def __setitem__(self, key, value):
        setattr(self.configuration, key, value)
    
    def save(self):
        with open(self.configuration_path, 'w') as f:
            f.write(dumps(self.configuration))
        
    def load(self):
        try:
            with open(self.configuration_path, 'r') as f:
                self.configuration = loads(f.read())
            return True
        except:
            return False

